package com.tz.online.cart.service.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tz.online.book.service.IBookService;
import com.tz.online.cart.service.IShoppingCart;
import com.tz.online.entity.Book;
import com.tz.online.entity.OrderItem;
import com.tz.online.util.BeanFactory;

@WebServlet(urlPatterns = "/cart/*")
public class CartAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8315374505680816746L;
	/** 业务接口 */
	private IShoppingCart shoppingCart;
	private IBookService bookService;
	/** 请求URL资源常量 */
	private static final String _SHOPPING = "/addCartAjax";// 添加到购物车
	private static final String _TO_SHOPPINGCART = "/showcart";// 查看购物车
	private static final String _MODIFYCART = "/modifyCartAjax";// 修改商品数量
	private static final String _REMOVE_CART = "/removeCartAjax";// 删除商品
	private static final String _CLEAR_CART = "/clearCartAjax";// 清空购物车

	public CartAction() {
		super();
		this.shoppingCart = (IShoppingCart) BeanFactory.getBean("cartService");
		this.bookService = (IBookService) BeanFactory.getBean("bookService");
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.获取 servletpath
		String servletPath = request.getServletPath();
		PrintWriter out = response.getWriter();
		if (servletPath.equals("/cart")) {
			// 拿到pathInfo
			String pathInfo = request.getPathInfo();
			// 根据pathInfo来决定不同处理
			switch (pathInfo) {
			case _SHOPPING:
				try {
					String bookId = request.getParameter("bookId");
					//根据bookid查询到book对象
					Book book = bookService.queryById(Long.valueOf(bookId));
					//创建商品详情对象
					OrderItem item = new OrderItem();
					/**封装商品详情对象*/
					item.setPrice(book.getPrice());
					item.setCount(1);
					item.setBookId(book.getId());
					item.setBookName(book.getBookName());
					item.setImageUrl(book.getImgUrl());
					//将商品详情添加到购物车中去
					shoppingCart.addCart(item);
					//并且将购物车放入到session作用域中
					request.getSession().setAttribute("shoppingCart", shoppingCart);
					//将所得到数据返回到页面
					out.print("1:" + shoppingCart.getCount() + ":" + shoppingCart.getTotal());
				} catch (Exception e) {
					// TODO: handle exception
					out.print("0");
					e.printStackTrace();
				}
				break;

			case _TO_SHOPPINGCART:
				//直接转发到购物车界面
				forward(request, response, true, "/WEB-INF/jsp/cart/cart.jsp");
				break;

			case _MODIFYCART:
				/* PrintWriter out = response.getWriter(); */
				try {
					/**接收页面发来的修改参数*/
					String bookId = request.getParameter("bookId");
					String count = request.getParameter("count");
					/**根据参数修改购物车的数据，成功没有异常就返回‘1’*/
					shoppingCart.modifyCount(Long.valueOf(bookId), Integer.parseInt(count));
					out.write("1");
				} catch (Exception e) {
					// TODO: handle exception
					/**有异常则返回'0'*/
					out.print("0");
					e.printStackTrace();
				}
				break;

			case _REMOVE_CART:
				try {
					/**接受发送来要删除的id字符串*/
					String ids = request.getParameter("ids");
					/**将id字符串分割成单个id数组，并且遍历这个数组，根据id来逐个删除商品信息,成功则返回'1'*/
					String[] arr = ids.substring(0, ids.length() - 1).split(":");// 把接收到的ID分开成数组
					for (String id : arr) {
						shoppingCart.delete(Long.valueOf(id));
					}
					out.print("1");
				} catch (Exception e) {
					// TODO: handle exception
					/**有异常返回'0'*/
					out.print("0");
					e.printStackTrace();
				}
				break;

			case _CLEAR_CART:
				try {
					/**调用购物车方法，将购物车清空，成功返回'1'*/
					shoppingCart.clear();
					out.print("1");
				} catch (Exception e) {
					/**失败返回'0'*/
					out.print("0");
					e.printStackTrace();
				}
				break;

			default:
				break;
			}

		}
	}
	/***************
	 * 转发或重定向请求
	 * 
	 * @param request
	 * @param response
	 * @param b
	 *            为真，则转换请求，为false,则重定向请求
	 * @param target
	 *            目标资源
	 * @throws IOException
	 * @throws ServletException
	 */
	private void forward(HttpServletRequest request, HttpServletResponse response, boolean b, String target)
			throws ServletException, IOException {
		if (b) {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(target);
			rd.forward(request, response);
			return;
		} else {
			String contextPath = getServletContext().getContextPath();
			response.sendRedirect(contextPath+target);
			return ;
		}
	}
}
